<template>
 <view class="uni-container">
   <view  class="uni-container-head">
		 <uv-search  v-model="searchValue" @change="search" @search="search" @clear="clear" placeholder="搜索"
		 @focus="true" @custom="search"></uv-search>
   </view>
   <scroll-view scroll-y="true" @scrolltolower="onScroll" style="height: 90vh;width: 100%;"  @scrolltoupper="onScrollTop">
   <view class="uni-list-view-content">
     <uni-card 
	 padding="0"
	 margin="0"
	 :is-shadow="false"
	 :border="false"
	 v-for="(item,index) in goods" :key="index"  @click="actionsClick('详情',item)" class="uni-card-shopping"
	 >
       <!-- <image mode="aspectFill" style="width: 100%;height: 100px;border-radius: 5px;"  
	   :src="'//wsrv.nl/?url='+item.mainImage"></image> -->
	   <image mode="aspectFill" style="width: 100%;height: 100px;border-radius: 5px;margin-top: 5px;"
	   :src="item.mainImage"></image>
	   <view style="display: flex;justify-content: space-between;margin-top: 8px;margin-bottom: 5px;">
			 <el-text style="font-weight: bold;font-size: 16px;">
				 {{item.goodsName}}
			 </el-text>
			 <el-text style="color: darkgray;">{{item.price}}元/{{item.unitName}}</el-text>
	   </view> 
       <view slot="actions" class="card-actions">
         <view class="card-actions-item" @click.stop="actionsClick('加入购物车',item)">
           <uni-icons type="cart-filled" size="25" color="#00aa7f"></uni-icons>
         </view>
         <view class="card-actions-item" @click.stop="actionsClick('咨询',item)">
           <uni-icons type="chat" size="25" color="#55aaff"></uni-icons>
         </view>
       </view>
     </uni-card>
	 <uni-popup ref="popup" background-color="#fff" @change="change">
	       <view class="popup-content" v-if="infoObj">
	         <view class="useraddress"   v-if="myaddress">
	           <view style="display: flex;width: 70%;">
	             <uni-icons type="location" size="20"></uni-icons> <text>{{myaddress.address}}{{myaddress.detailAddress}} {{myaddress.name}} {{myaddress.phone}}</text>
	           </view>
	           <view style="text-align: right;width: 30%;display: flex;align-items: flex-start;justify-content: flex-start;">
	             <text  style="color: darkgray;">默认</text>
				 <button @click="goToReceivingAddress" type="primary" style="border: none;padding-left: 5px;padding-right: 5px;" size="mini">选择</button>
	           </view>
	         </view>
			 <view  v-if="!myaddress"  class="useraddress" style="justify-content: space-between;">
				 <text  style="color: darkgray;width: 70%;">请填写收货地址</text>
				 <button @click="goToReceivingAddress" type="primary" style="border: none;" size="mini">选择</button>
			 </view>
	         <view class="infos">
	           <image :src="infoObj.mainImage" class="image"></image>
	           <view class="info">
	             <view style="margin-bottom: 5px;display: flex;justify-content: space-between;">
					 <text style="font-size: 16px;font-weight: bold;">{{infoObj.goodsName}}</text>
					 <text style="font-size: 14px;">价格：{{infoObj.price*quantity}}</text>
				 </view>
	             <view style="display: flex;justify-content: space-between;font-size: 14px;">
				   <text>单价：{{infoObj.price}}元</text>
	               <text>剩余数量：{{infoObj.supplyQuantity ? infoObj.supplyQuantity:0}}</text>
	             </view>
				 <view>
				   <uni-number-box :min="1" :max="12" :value="quantity" v-model="quantity"/>
				 </view>
	           </view>
	         </view>
	         <view class="choose">
			   <view style="padding: 5px;font-size: 14px;" v-if="infoObj.weights.length > 0">
				   <view>
					   重量
				   </view>
				   <view style="margin-top: 5px;">
					   <button style="margin-right: 5px;" size="mini" v-for="(item,index) in infoObj.weights"
					   :key="index" :class="{'active':index === currentIndex}" @click="selectButton(item.id,index)">{{item.weight}}{{item.weightUnitName}} {{item.price}}元</button>
				   </view>
			   </view>
			   <view style="padding: 5px;font-size: 14px;" v-if="infoObj.sizes.length > 0">
				   <view>
					尺寸
				   </view>
				   <view style="margin-top: 5px;">
					   <span  v-for="(item,index) in infoObj.sizes"
					   :key="index">
						   <button v-if="item.sizeName"  style="margin-right: 5px;" size="mini" :class="{'activeSize':index === currentIndexSize}" @click="selectButtonSize(item.id,index)">{{item.sizeName}}</button>
					   </span>
				   </view>
			   </view>
			   <view  style="padding: 5px;font-size: 14px;"  v-if="infoObj.colorClassicList.length > 0">
				   <view>颜色分类</view>
				   <view  style="margin-top: 5px;" v-for="(item,index) in infoObj.colorClassicList">
					   <button style="margin-right: 5px;" size="mini" 
					   :key="index" :class="{'activeColorClassic':index === currentIndexColorClassic}" @click="selectButtonColorClassic(item.id,index)">
					   {{item.color}} {{item.goodsSubName}} 【{{item.style}}】{{item.additional}} {{item.remark}}
					   </button>
				   </view>
			   </view>
	         </view>
			 <view class="uni-btn">
			   <button type="primary" plain size="mini" style="margin-right: 20px" @click="payBtn">立即支付</button>
			   <button type="info" plain size="mini" @click="close">取消</button>
			 </view>
	       </view>
	     </uni-popup>
   </view>
    </scroll-view>
</view>
</template>

<script setup lang="ts">
import { onLaunch, onLoad } from '@dcloudio/uni-app'
import { nextTick, onMounted, ref } from 'vue'
import * as url from "node:url";
import {page,info} from '@/api/goods.ts'
import {getWxPayInfo,saveOrder} from '@/api/order.ts'
import {pageReceive} from '@/api/receiveaddress.ts'
import {baseUrl} from '@/api/request.ts'

const onScroll =(e)=> {
  console.log('滚动到底部了');
  if(goods.value.length < total.value && total.value > 0){
	  queryParams.value.page++;
	  getGoods()
  }
}
const onScrollTop =(e)=> {
  console.log('滚动到顶部了');
  queryParams.value.page=1;
  getGoods()
}
const payBtn=()=>{
	if(quantity.value == 0){
		uni.showToast({
			title:'数量不能为空'
		})
		return;
	}
	if(productSpecificationsIds.value.length == 0){
		uni.showToast({
			title:'规格不能为空'
		})
		return;
	}
	if(!myaddress.value){
		uni.showToast({
			title:'收货地址不能为空'
		})
		return;
	}
	if(infoObj.value.supplyQuantity == null || infoObj.value.supplyQuantity==0){
		uni.showToast({
			title:'供应量不足'
		})
		return;
	}
	saveOrder({"goodsId":infoObj.value.id,"receivingAddressId":myaddress.value.id,
	"placeOrderQuantity":quantity.value,"placeOrderUnitPrice":infoObj.value.price,
	"productSpecificationsIds":productSpecificationsIds.value.join(',')}).then(ressave=>{
		if(ressave.code==200){
			getWxPayInfo({"amount":infoObj.value.price*quantity.value,"orderId":ressave.data}).then(res=>{
				// 仅作为示例，非真实参数信息。
				uni.requestPayment({
				    provider: 'wxpay',
					timeStamp: res.data.timeStamp,
					nonceStr: res.data.nonceStr,
					package: res.data.packageVal,
					signType: res.data.signType,
					paySign:  res.data.paySign,
					success: function (res) {
						console.log('success:' + JSON.stringify(res));
						popup.value.close()
					},
					fail: function (err) {
						console.log('fail:' + JSON.stringify(err));
					}
				});
			})
		}
	})
}
const productSpecificationsIds=ref([])
const currentIndex=ref(-1) 
const selectButton=(id,index)=>{
	currentIndex.value=index
	productSpecificationsIds.value.push(id)
}
const currentIndexSize=ref(-1) 
const selectButtonSize=(id,index)=>{
	currentIndexSize.value=index
	productSpecificationsIds.value.push(id)
}
const currentIndexColorClassic=ref(-1) 
const selectButtonColorClassic=(id,index)=>{
	currentIndexColorClassic.value=index
	productSpecificationsIds.value.push(id)
}
const cover=ref('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg')
const avatar = ref('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png')
const searchValue=ref()
const search=(res)=> {
  queryParams.value.keyword=searchValue.value
  queryParams.value.page=1
  getGoods()
}
const clear=(res)=> {
  searchValue.value=null
  queryParams.value.keyword=null
  queryParams.value.page=1
  getGoods()
}
const popup=ref()
const actionsClick=(text,item)=>{
  if (text == '详情'){
    uni.navigateTo({
      url:'/pages/goods/detail?id='+item.id,
    })
  }else if (text == '咨询'){
    uni.navigateTo({
      url:'/pages/message/detail?shopId='+item.shopId
    })
  }else if (text == '加入购物车'){
     popup.value.open('bottom')
	 productSpecificationsIds.value=[]
	 getInfo(item.id)
	 getDefaultAddress()
  }
}
const myaddress=ref()
const getDefaultAddress=()=>{
	pageReceive({"defaulted":'1'}).then(res=>{
		if(res.data.list.length > 0){
			myaddress.value=res.data.list[0]
		}
	})
}
const infoObj=ref()
const getInfo=(id)=>{
	info(id).then(res=>{
		infoObj.value=res.data
	})
}
const change=(e)=> {
  console.log('当前模式：' + e.type + ',状态：' + e.show);
}
const close=()=>{
  popup.value.close()
}
const goToReceivingAddress=()=>{
  uni.navigateTo({
    url:'/pages/receivingaddress/index'
  })
}
const quantity=ref(0)
const goods=ref([])
const queryParams=ref({
	page:1,
	limit:10,
	keyword:null,
})
const total=ref(0)
const getGoods=()=>{
	page(queryParams.value).then(res=>{
		if(queryParams.value.page == 1){
			goods.value=res.data.list
		}else{
			goods.value=goods.value.concat(res.data.list)
		}
		total.value=res.data.total
	})
}
onMounted(()=>{
	getGoods()
})
</script>

<style lang="scss">
.active{
	color: orangered;
	border:1px solid orangered;
}	
.activeSize{
	color: orangered;
	border:1px solid orangered;
}	
.activeColorClassic{
	color: orangered;
	border:1px solid orangered;
}
.uni-btn{
  padding: 10px;
  width: 100%;
  text-align: center;
  position: static;
  bottom: 0;
}	
.image{
  width: 25%;height: 80px;border-radius: 5px;
}	
.infos{
  display: inline-flex;
  width:100%;
}
.info{
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  width: 75%;
  height: 100%;
}
.choose{
  width: 100%;
  height: auto;
  overflow-y: auto;
}
.choose::-webkit-scrollbar{
	display: none;
}
.popup-content {
  padding: 20px;
  height: auto;
  max-height: 60vh;
  position: relative;
  overflow: auto;
}
.popup-content-shopping{
  padding: 20px;
  height: auto;
}
.shopping-info text{
  padding: 2px;
}
.shopping-info image{
  border-radius: 5px;
  width: 50px;height: 50px;
}
.useraddress{
  padding-bottom: 10px;
  height: 10%;
  width: 100%;
  margin-bottom: 5px;
  display: flex;
  font-size: 14px;
}	
	

.uni-list-view-content{
  margin-top: 5px;
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* 三列等宽 *//* 自动填充列，每列最小宽度150px，最大宽度根据可用空间自动调整 */
  gap: 0px; /* 卡片之间的间距 */
  justify-content: center;
  align-items: center;
  width: 100%;
  // overflow: auto;
  padding: 4px;
}
.uni-list-view-content::webkit-scrollbar{
	// display: none;
}
.uni-card-shopping{
	width: 100%;
	height: 100%;
	padding: 0px;
	margin-bottom: 5px;
	border-bottom: 1px solid lightgray;
}
.card-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 35px;
  border-top: 1px #eee solid;
}
.card-actions-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0px;
}
.card-actions-item-text {
  font-size: 12px;
  margin-left: 5px;
}
	.uni-container {
    width: 100%;
    height: 100%;
	position: relative;
  }
  .uni-container-head {
	width: 94%;
	position: sticky;
	top: 0; /* 或者根据需要调整位置 */
	left: 0; /* 或者根据需要调整位置 */
	z-index: 100; /* 确保它在上面 */
	background-color: white;
	padding: 10px;
	margin-top: 0px;
  }
  .uni-cover-image{
    height: 150px;
    width: 100%;
    margin: 10rpx;
	border-radius: 5px;
  }
  .search{
    margin: 10rpx;
  }
</style>
